﻿using System;
using System.Collections.Generic;

using System.Threading;
using System.Threading.Tasks;



namespace DailyFx.UI
{
	/// <summary>
	///		for mediator .
	/// </summary>
	public class BackgroundTaskManager // : TaskScheduler
	{
		/// <summary>
		///		the task queue on background .
		/// </summary>
		private readonly Dictionary< object, Task<object> > _taskQueue;

		/// <summary>
		///		the factory creating general background task .
		/// </summary>
		private readonly TaskFactory _factory;


		/// <summary>
		/// 
		/// </summary>
		public BackgroundTaskManager ()
		{
			this._taskQueue = new Dictionary <object, Task<object>> ();
			this._factory = new TaskFactory ( TaskCreationOptions.LongRunning, TaskContinuationOptions.None );
		}


		/// <summary>
		/// 
		/// </summary>
		public bool RunTask ( object target, Delegate action,  object[] args )
		{
			if ( this._taskQueue.ContainsKey( target) )
				return false;

			  var task = this._factory.StartNew( () => action.DynamicInvoke(args) );
			this._taskQueue.Add ( target, task );

			return true;
		}
	}
}
